package org.jeecg.modules.vinQuery.service;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class WebDriverManager {

    @Value("${webdriver.edge.driver}")
    private String edgeDriverPath;
    @Value("${webdriver.chrome.driver}")
    private String chromeDriverPath;

    private final Map<String, WebDriver> drivers = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        // 初始化配置，如设置ChromeOptions等
        // 设置EdgeDriver路径
        System.setProperty("webdriver.edge.driver", edgeDriverPath);
//        System.setProperty("webdriver.chrome.driver", chromeDriverPath);
    }

    @PreDestroy
    public void cleanup() {
        for (WebDriver driver : drivers.values()) {
            if (driver != null) {
                driver.quit();
            }
        }
    }

    @Scheduled(cron = "0 0 22 * * ?")
    public void scheduledCleanup() {
        cleanup();
    }

    public synchronized WebDriver createDriver(String openId) {
        if (!drivers.containsKey(openId)) {
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--headless", "window-size=1920,1080");
//            WebDriver driver = new ChromeDriver(options);
            WebDriver driver = new EdgeDriver();
            drivers.put(openId, driver);
        }
        return drivers.get(openId);
    }

    public WebDriver getDriver(String openId) {
        return drivers.get(openId);
    }

    public void removeDriver(String openId) {
        WebDriver driver = drivers.remove(openId);
        if (driver != null) {
            driver.quit();
        }
    }

}
